package com.coupon.couponbatchsend100w.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
public class ThreadPoolConfig {
    @Value("${thread.pool.corePoolSize}")
    private int corePoolSize;

    @Value("${thread.pool.maxPoolSize}")
    private int maxPoolSize;

    @Value("${thread.pool.queueCapacity}")
    private int queueCapacity;

    @Value("${thread.pool.keepAliveSeconds}")
    private int keepAliveSeconds;

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
//        新建spring版本的线程池，它比juc的那个好使
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();

//        设置核心线程池大小：
        threadPool.setCorePoolSize(corePoolSize);
//        最大可创建的线程数：
        threadPool.setMaxPoolSize(maxPoolSize);
//        等待队列最大长度：
        threadPool.setQueueCapacity(queueCapacity);
//        设置线程池维护空闲线程的最大存活时间
        threadPool.setKeepAliveSeconds(keepAliveSeconds);
//        异步方法内部线程名称：
        threadPool.setThreadNamePrefix("spring默认线程池-");
//        线程池对拒绝任务（无线程池可用的）处理策略
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//        任务都完成再关闭线程池：
        threadPool.setWaitForTasksToCompleteOnShutdown(true);
//        任务初始化：
        threadPool.initialize();

        return threadPool;

    }
}
